package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Measurement;
import model.Sensor;
import DAO.MeasurementsDao;
import DAO.SensorDao;
import database.DBManager;

/**
 * Servlet implementation class CameraServlet
 */
public class WarningServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DBManager myDb;
   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WarningServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init( ServletConfig servletconfig ) {
		// Initialisatie
		myDb = ( DBManager ) servletconfig.getServletContext().getAttribute( "dbmanager" );
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher("index.jsp");
		}else if(!gotAuth(request)){
			view = request.getRequestDispatcher("SensorServlet?page=home");
		}else{
			Logger.createLog(request);
			SensorDao sdao = new SensorDao(myDb);
			ArrayList<Sensor> sensors = sdao.getSensors();
			request.setAttribute("sensors", sensors);
			view = request.getRequestDispatcher( "WEB-INF/warn.jsp" );
		}
		request = getWarningInfo(request);
		view.forward( request, response );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher("index.jsp");
		}else if(!gotAuth(request)){
			view = request.getRequestDispatcher("SensorServlet?page=home");
		}else{
			Logger.createLog(request);
			String[] url = request.getQueryString().split( "=" );
			if( url[0].equals("page") && url[1].equals("update")) {
				SensorDao sdao = new SensorDao(myDb);
				ArrayList<Sensor> sensors = sdao.getSensorsWithoutMeasurements();
				double tempmax = sensors.get(3).getMaxValue();
				double luchtmax = sensors.get(4).getMaxValue();
				//als er rare waarden ingevuld worden; gebruik gewoon oude waarden
				try{
					tempmax = Double.parseDouble(request.getParameter("tempmax"));
				}catch(Exception ex){
					ex.printStackTrace();
				}
				try{
					luchtmax = Double.parseDouble(request.getParameter("luchtmax"));
				}catch(Exception ex){
					ex.printStackTrace();
				}
				sdao.updateSensor(tempmax, 4);  //temperatuur
				sdao.updateSensor(luchtmax, 5); //lucht
				request.setAttribute("url", "WarningServlet");
				view = request.getRequestDispatcher( "/WEB-INF/redirect.jsp" );
			}
		}
		request = getWarningInfo(request);
		view.forward( request, response );
	}
	
	private boolean isLoggedIn(HttpServletRequest request){
		HttpSession session = request.getSession();
		boolean loggedIn = false;
		if(session.getAttribute("logged") != null){
			if(session.getAttribute("logged").equals("true")){
				loggedIn = true;
			}
		}
		return loggedIn;
	}
	
	private boolean gotAuth(HttpServletRequest request){
		HttpSession session = request.getSession();
		boolean gotAuth = false;
		if(session.getAttribute( "rollID" ) != null){
			int rollId = (Integer) session.getAttribute("rollID");
			if(rollId == 1){
				gotAuth = true;
			}
		}
		return gotAuth;
	}
	
	private HttpServletRequest getWarningInfo(HttpServletRequest request){
		MeasurementsDao md = new MeasurementsDao(myDb);
		ArrayList<Measurement> latestMeasurements = new ArrayList<Measurement>();
		for(int i = 1; i <= 5; i++){
			Measurement measurement = md.getLatestMeasurementByID(i);
			if(measurement != null){
				latestMeasurements.add(measurement);
			}
		}
		SensorDao sdao = new SensorDao(myDb);
		ArrayList<Sensor> sensors = sdao.getSensors();
		request.setAttribute("sensorsmax", sensors);
		request.setAttribute("latestMeasurements", latestMeasurements);
		return request;
	}
}